<script lang="ts" setup>
import { ElFile, UploadFile } from 'element-plus/lib/components/upload/src/upload.type'
import { onBeforeMount, reactive, ref } from 'vue'
import { saveUploadFileUrl } from "/@/api/org/file-attachment"
import { getAccessToken } from '/@/utils/common'
import userBeanServiceApi from '/@/api/org/bean/user-bean'

const emit = defineEmits<{
    (e: 'updateAvatar', val: any): any
}>()
const uploadAvatarRef = ref()
const avatarUploadState = reactive({
    fileList: [],
    // 附带参数
    extraData: {
        itemType: "userImg",
        busiId: "userImg",
        compId: "org"
    },
    headers: {
        Authorization: null as unknown as String
    },
    handleAvatarSuccess: (res: any, file: UploadFile) => {
        if (res[0].fileId) {
            userBeanServiceApi.updateUserImage({ fileId: res[0].fileId }).then().catch((err) => {
                console.log(err)
            })
            uploadAvatarRef.value.clearFiles()
            emit('updateAvatar', res[0].fileId)
        }
    },
    beforeAvatarUpload: (file: ElFile) => {
        // 类型 大小限制
        const isJPG = file.type === 'image/jpeg'
        const isLt2M = file.size / 1024 / 1024 < 5
        if (!isJPG) {
            // ElMessage.error('Avatar picture must be JPG format!')
        }
        if (!isLt2M) {
            // ElMessage.error('Avatar picture size can not exceed 5MB!')
        }
        // return isJPG && isLt2M
    }
})
onBeforeMount(() => {
    let token = getAccessToken()
    avatarUploadState.headers['Authorization'] = "bearer " + token
})

</script>
<template>
    <el-upload
        ref="uploadAvatarRef"
        class="upload-demo"
        :action="saveUploadFileUrl"
        :multiple="false"
        :limit="1"
        name="files"
        :file-list="avatarUploadState.fileList"
        :headers="avatarUploadState.headers"
        :data="avatarUploadState.extraData"
        :on-success="avatarUploadState.handleAvatarSuccess"
        :before-upload="avatarUploadState.beforeAvatarUpload"
        :show-file-list="false"
    >
        <jxtech-svg-icon :icon="'#icon-confirm'" :size="24" class="pointer"></jxtech-svg-icon>
        <span>修改头像</span>
    </el-upload>
</template>
<style scoped lang="scss">
::v-deep(.el-upload--text) {
    display: flex;
    align-items: center;
}
::v-deep(.el-upload-list) {
    display: none;
}
</style>